<template>
  <div class="invisible-barcode">
    <div class="barcode" ref="barcode">
      <div class="barcode-title">商品名称：{{ codeDetail.goodName }}</div>
      <div class="barcode-title">价格：{{ codeDetail.retailPrice }}（元）</div>
      <img
        :src="'https://fx.fangxi666.com/prod-api' + codeDetail.qrCodeUrl"
        class="barcode-img"
      />
    </div>
  </div>
</template>
<script>
import { DTPWeb } from "dtpweb";
import html2canvas from "html2canvas";
export default {
  name: "Barcode",
  components: {},
  mixins: [],
  props: {
    codeDetail: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      api: null,
      imgUrl: null,
    };
  },
  computed: {},
  watch: {
    codeDetail(value) {
      this.$nextTick(() => {
        for (let i = 0; i < value.count; i++) {
          this.getDocument();
        }
      });
    },
  },
  mounted() {
    this.api = DTPWeb.getInstance();
    // this.detectionPrinter();
  },
  methods: {
    // 获取元素
    getDocument() {
      this.$nextTick(() => {
        const element = this.$refs["barcode"];
        html2canvas(element, {
          useCORS: true,
          allowTaint: true,
        }).then((canvas) => {
          this.imgUrl = canvas.toDataURL();
          // console.log(this.imgUrl);
          // return
          if (!this.api) return;
          this.api.openPrinter();
          this.startPrinte();
          // this.api.closePrinter();
        });
      });
    },
    // 检测打印机
    detectionPrinter() {
      let status = false;
      DTPWeb.checkServer({
        callback: (api, server) => {
          this.api = api;
          if (!api) {
            alert("未检测到打印机助手，请先安装打印机助手才能打印小票！");
            status = true;
          }
        },
      });
      return status;
    },
    //
    // 开始打印
    startPrinte() {
      this.api.setParam({ id: 1, value: 2 });
      this.api.printImage({
        data: this.imgUrl,
        printerName: this.currPrinter?.name,
        copies: 1,
        orientation: this.currOrientation,
        gapType: 2,
      });
      this.api.commitJob({
        callback: () => {
          // 打印完毕后关闭打印机
          this.api.closePrinter();
        },
      });
    },
    printRawData(rawData, callback) {
      const printer = this.currPrinter || {};
      return this.api.printRawData({
        // 打印数据，支持 Uint8Array，base64字符串，16进制字符串等格式的数据。
        data: rawData,
        // 打印机名称
        printerName: printer.name,
        // 打印份数
        // copies: 1,
        // 打印任务名称
        // jobName: "",
        callback: (res) => {
          callback && callback(res);
        },
      });
    },
    onPrintRawData() {
      if (!this.printData || this.printData.length <= 0) {
        console.warn(`---- 未检测到打印数据！`);
        return;
      }
      const pageList = this.printData.map((v) => v.join(""));
      this.printRawList(pageList, 0);
    },
    // 获取打印机信息
    getPrinterName() {
      let printerName = this.api.getPrinterName();
      console.log(8888888, printerName);
    },
    updatePrinterList() {
      let status = false;
      if (!this.api) {
        alert("打印助手异常");
        return;
      }
      //
      const api = this.api;
      //
      api.getPrinters({
        onlyOnline: false,
        onlyLocal: true,
        callback: (values) => {
          // 清空旧打印机列表
          //
          if (values?.length > 0) {
            for (const item of values) {
              const title = api.isLocalPrinter(item)
                ? item.deviceName || item.name
                : `${item.deviceName || item.name}@${item.ip}`;
              this.printers.push({
                name: title,
                value: item,
              });
            }
          } else {
            alert("未检测到打印机信息，请先连接打印机！");
            this.printers.push({ name: "未检测到打印机", value: "" });
            status = true;
          }
          //
          this.currPrinter = this.printers[0].value;
        },
      });
      return status;
    },
    close() {
      this.api.closePrinter();
    },
  },
};
</script>
<style lange='sass' scoped>
.barcode {
  width: 500px;
  height: 260px;
  display: flex;
  padding: 40px;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;

  .barcode-title {
    font-size: 26px;
    margin-left: 150px;
    text-align: left;
    width: 100%;
  }

  .barcode-img {
    height: 30%;
    width: 70%;
  }
}

.invisible-barcode {
  position: absolute;
  top: -888px;
  left: -888px;
  opacity: 0;
  pointer-events: none;
}
</style>